package com.lagou.boot;

import com.lagou.client.RPCConsumer;
import com.lagou.handler.DurationCounterHandler;
import com.lagou.service.IUserService;
import com.lagou.util.ZkCuratorUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ConsumerBoot {

    //参数定义
//    private static final String PROVIDER_NAME = "UserService#sayHello#";

    public static void main(String[] args) throws InterruptedException {

        //1.创建代理对象
        RPCConsumer rpcConsumer = new RPCConsumer();
        IUserService proxy = (IUserService) rpcConsumer.createProxy(IUserService.class);
        // TODO
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
        ZkCuratorUtils zkClient = new ZkCuratorUtils();
        DurationCounterHandler durationHandler = new DurationCounterHandler(zkClient);
        executorService.schedule(durationHandler, 5l, TimeUnit.SECONDS);

        while (true) {
            long startTime = System.currentTimeMillis();
            System.out.println("=======>>>clinet send message to server:");

            try {

                Thread.sleep(2000);
                String result = proxy.sayHello("success");
                System.out.println(result);
                if (result == null) {
                    continue;
                }
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                Thread.sleep(2000);
                durationHandler.setDuration(duration);
                String prefix = "server[";
                String hostAndPort = result.substring(result.indexOf(prefix) + prefix.length(), result.indexOf("]"));
                durationHandler.setHostAndPort(hostAndPort);
                executorService.submit(durationHandler);
            } catch (Exception e) {
                int step = 0;
                while (proxy == null && ++step <= 3) {
                    proxy = (IUserService) rpcConsumer.createProxy(IUserService.class);
                }
                System.out.println("尝试重复连接次数：" + step);
                e.printStackTrace();
            }
        }
    }
}
